** Preparing control variables

* Election results

// Presidential elections
use "$project_path/data/3_cleaned/presidential_elections", clear
gen nb_candidates = .
forvalues i=1/50 {
	gen double share_`i' = Vote_Share1_`i'
	replace share_`i' = Vote_Share2_`i' if flag_two_round==1
	replace share_`i' = E_Vote_Share1_`i' if flag_indirect==1 & E_Vote_Share1_1!=.
	replace share_`i' = E_Vote_Share2_`i' if flag_indirect==1 & E_Vote_Share2_1!=.
	replace share_`i' = E_Vote_Share3_`i' if flag_indirect==1 & E_Vote_Share3_1!=.
	replace nb_candidates = `i' if Candidate_`i'!=""
}
keep Country Year Month Type_Election share_1 nb_candidates
merge 1:1 Country Year Month using "$project_path/data/3_cleaned/turnovers_presidential", nogen
ren share_1 share_winner
keep Country Year Month Type_Election share_winner share_incumbent nb_candidates flag_not_last
tempfile pres
save `pres'

// Parliamentary elections
use "$project_path/data/3_cleaned/parliamentary_elections", clear
keep Country Year Month Type_Election Seat_Share*
merge 1:1 Country Year Month Type_Election using "$project_path/data/3_cleaned/turnovers_parliamentary_electoral", nogen
gen share_winner = Seat_Share_1
gen nb_candidates = 0
forvalues i=1/74 {
	replace nb_candidates = `i' if  Seat_Share_`i' !=.
}
keep Country Year Month Type_Election share_winner share_incumbent nb_candidates flag_not_last

append using `pres'

// Neighboring elections outcomes
drop if flag_not_last==1
sort Type_Election Country Year Month
foreach v in share_winner share_incumbent {
	gen lag_`v' = `v'[_n-1] if Country==Country[_n-1]
	gen for_`v' = `v'[_n+1] if Country==Country[_n+1]
}

tempfile shares
save `shares'

* Ideology variables
// Winner, presidential elections
use "$project_path/data/1_input/elections/Wikipedia_links/links_pres", clear
keep Country Year Month Type_Election Candidate left_right_score populism illiberalism
ren Candidate Candidate_1
ren left_right_score left_right_winner
ren populism populism_winner
ren illiberalism illiberalism_winner
tempfile ideology_pres_winner
save `ideology_pres_winner'
// Runner-up, presidential elections
use "$project_path/data/1_input/elections/Wikipedia_links/links_pres", clear
keep Country Year Month Type_Election Candidate left_right_score populism illiberalism
ren Candidate Candidate_2
ren left_right_score left_right_runner_up
ren populism populism_runner_up
ren illiberalism illiberalism_runner_up
tempfile ideology_pres_runner_up
save `ideology_pres_runner_up'
// Winner, parliamentary elections
use "$project_path/data/1_input/elections/Wikipedia_links/links_parl", clear
keep Country Year Month Type_Election Party left_right_score populism illiberalism
ren Party Party_1
ren left_right_score left_right_winner
ren populism populism_winner
ren illiberalism illiberalism_winner
tempfile ideology_parl_winner
save `ideology_parl_winner'
// Runner-up, parliamentary elections
use "$project_path/data/1_input/elections/Wikipedia_links/links_parl", clear
keep Country Year Month Type_Election Party left_right_score populism illiberalism
ren Party Party_2
ren left_right_score left_right_runner_up
ren populism populism_runner_up
ren illiberalism illiberalism_runner_up
tempfile ideology_parl_runner_up
save `ideology_parl_runner_up'
// Presidential elections
use "$project_path/data/3_cleaned/presidential_elections", clear
merge 1:1 Country Year Month Type_Election Candidate_1 using `ideology_pres_winner', keep(master match) nogen
merge 1:1 Country Year Month Type_Election Candidate_2 using `ideology_pres_runner_up', keep(master match) nogen
keep Country Year Month Type_Election left_right_winner populism_winner illiberalism_winner left_right_runner_up populism_runner_up illiberalism_runner_up
tempfile ideology_pres
save `ideology_pres'
// Parliamentary elections
use "$project_path/data/3_cleaned/parliamentary_elections", clear
merge 1:1 Country Year Month Type_Election Party_1 using `ideology_parl_winner', keep(master match) nogen
merge 1:1 Country Year Month Type_Election Party_2 using `ideology_parl_runner_up', keep(master match) nogen
keep Country Year Month Type_Election left_right_winner populism_winner illiberalism_winner left_right_runner_up populism_runner_up illiberalism_runner_up
append using `ideology_pres'
// Ideology controls
gen distance_wr_left_right = left_right_winner - left_right_runner_up
gen distance_wr_populism = populism_winner - populism_runner_up
gen distance_wr_illiberalism = illiberalism_winner - illiberalism_runner_up
drop left_right_runner_up populism_runner_up illiberalism_runner_up
tempfile ideology
save `ideology'

* Pre-election conditions

use "$project_path/data/4_regdata/regdata", clear
drop if runvar==.

gen decade = Year - mod(Year, 10)
tab decade, gen(d_decade)
tab Region, gen(d_region)
tab reg_type, gen(d_reg_type)
keep Country Year Month Type_Election runvar d_decade* d_region* d_reg_type* OECD lagged_growth_gdpc_penn lagged2_growth_gdpc_penn lagged_inflation_imf lagged2_inflation_imf lagged_unemployment_ilo lagged2_unemployment_ilo lagged_trade_wb lagged2_trade_wb lagged_hdi lagged2_hdi lagged_democracy_index lagged2_democracy_index std_diff_m1_growth_gdpc_penn std_diff_m1_inflation_imf std_diff_m1_unemployment_ilo std_diff_m1_trade_wb std_diff_m1_hdi std_diff_m1_democracy_index 
merge 1:1 Country Year Month Type_Election using `shares', assert(using match) keep(match) nogen
merge 1:1 Country Year Month Type_Election using `ideology', assert(using match) keep(match) nogen

** Defining sets of controls

//Restricted set
local pre_controls = "d_decade* d_region* OECD"
foreach v in lagged_growth_gdpc_penn lagged2_growth_gdpc_penn lagged_inflation_imf lagged2_inflation_imf lagged_unemployment_ilo lagged2_unemployment_ilo lagged_trade_wb lagged2_trade_wb lagged_hdi lagged2_hdi lagged_democracy_index lagged2_democracy_index nb_candidates left_right_winner populism_winner illiberalism_winner distance_wr_left_right distance_wr_populism distance_wr_illiberalism {
	gen c_`v' = `v'
	gen m_`v' = (`v'==.)
	replace c_`v' = 0 if m_`v'==1
	local pre_controls = "`pre_controls' c_`v' m_`v'"
}

//Full set + post outcomes
local post_controls = ""
foreach v in std_diff_m1_growth_gdpc_penn std_diff_m1_inflation_imf std_diff_m1_unemployment_ilo std_diff_m1_trade_wb std_diff_m1_hdi std_diff_m1_democracy_index {
	gen c_`v' = `v'
	gen m_`v' = (`v'==.)
	replace c_`v' = 0 if m_`v'==1
	local post_controls = "`post_controls' c_`v' m_`v'"
}

sum `pre_controls'
sum `post_controls'

** Measures of quality

gen evolution_share_winner = for_share_incumbent - share_winner
order evolution_share_winner share_winner for_share_incumbent, after(Type_Election)

reg evolution_share_winner `pre_controls'
predict quality_pre, resid

reg evolution_share_winner `pre_controls' `post_controls'
predict quality_pre_post, resid

** Regressions 

log using "$project_path/output/appendix_tables/Appendix_Table_E8.smcl", replace

rdrobust evolution_share_winner runvar, all
rdrobust quality_pre runvar, all
rdrobust quality_pre_post runvar, all

log close

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
	
	rdrobust evolution_share_winner runvar, all
	local b_none: di %5.2f e(tau_cl)
	local se_none: di %5.2f e(se_tau_rb)
	local p_none: di %5.3f e(pv_rb)
	local N_none: di %6.0f e(N)

	rdrobust quality_pre runvar, all
	local b_pre: di %5.2f e(tau_cl)
	local se_pre: di %5.2f e(se_tau_rb)
	local p_pre: di %5.3f e(pv_rb)
	local N_pre: di %6.0f e(N)

	rdrobust quality_pre_post runvar, all
	local b_pre_post: di %5.2f e(tau_cl)
	local se_pre_post: di %5.2f e(se_tau_rb)
	local p_pre_post: di %5.3f e(pv_rb)
	local N_pre_post: di %6.0f e(N)

	//Prepare matrix of coefficients and other statistics
	mat Coefs = J(4, 6, .)
	
	mat Coefs[1,1] = `b_none'
	mat Coefs[2,1] = `se_none'
	mat Coefs[1,4] = `p_none'
	mat Coefs[4,1] = `N_none'
	
	mat Coefs[1,2] = `b_pre'
	mat Coefs[2,2] = `se_pre'
	mat Coefs[1,5] = `p_pre'
	mat Coefs[4,2] = `N_pre'
	
	mat Coefs[1,3] = `b_pre_post'
	mat Coefs[2,3] = `se_pre_post'
	mat Coefs[1,6] = `p_pre_post'
	mat Coefs[4,3] = `N_pre_post'


	clear
	svmat Coefs

	//	input variable names
	input str22 varname 
	"Electoral turnover"
	"SE"
	"Controls"
	"N"

	replace varname = "" if varname == "SE"
	replace varname = "" if varname == "SE"
	order varname
	
	// Rename cols and labels
	rename Coefs1 Model1
	rename Coefs2 Model2
	rename Coefs3 Model3
	rename Coefs4 P_Model1
	rename Coefs5 P_Model2
	rename Coefs6 P_Model3
	
	label var varname ""
	label var Model1 "(1)"
	label var Model2 "(2)"
	label var Model3 "(3)"
	
	// Convert to string, add parentheses to SEs, and add options
	forvalues i = 1/3{
		
		format Model`i' %04.2f
		tostring Model`i', replace force format(%04.2f)
		replace Model`i'= "" if Model`i'=="."
		replace Model`i' = "(" + Model`i' + ")" if missing(varname) & Model`i' !=""	
		
		if `i' == 1{
			replace Model`i' = "None" if varname == "Controls" & Model`i' ==""
		}
		if `i' == 2{
			replace Model`i' = "Pre-election" if varname == "Controls" & Model`i' ==""
		}
		if `i' == 3{
			replace Model`i' = "Pre and post-election" if varname == "Controls" & Model`i' ==""
		}
		
		replace Model`i' = substr(Model1, 1, 4) if varname == "N"
		
	}

	// Add stars
	local 3_star_threshold 0.01
	local 2_star_threshold 0.05
	local 1_star_threshold 0.10
	
	forvalues i = 1/3{
		
		replace Model`i' = Model`i' + "\sym{***}" if P_Model`i' < `3_star_threshold'
		replace Model`i' = Model`i' + "\sym{**}" if P_Model`i' < `2_star_threshold' & P_Model`i' > `3_star_threshold'
		replace Model`i' = Model`i' + "\sym{*1}" if P_Model`i' < `1_star_threshold' & P_Model`i' > `2_star_threshold'
		
		drop P_Model`i'
		
	}
	
	texsave using "$project_path/output/appendix_tables/Appendix_Table_E8.tex", 	///
			      hlines(2) size(normalsize) rowsep(0.12cm) width(15cm) label("tab:winner_quality") ///
				  title("Change in proxies for winner quality at the threshold") frag varlabel nofix location(H)	replace	///
				  footnote("\emph{Notes}: In this table, we show RD estimates of the change at the threshold in proxies for the quality of the winner of election \emph{t}. In column (1), quality is measured as the change in the vote share of the winner between \emph{t+1} and \emph{t}. In column (2), quality is measured as the residual of a regression of the change in the vote share of the winner on a set of pre-election controls, including decade and region dummies; a dummy indicating OECD membership; the value of our main outcomes in the two years before the election; the number of candidates competing in the election; the left-right score, populism score, and illiberalism score of the winner; and the distance in these ideology measures between the winner and the runner-up. In column (3), quality is measured as the residual of a regression of the change in the vote share of the winner on the set of pre-election controls, as well as our main measures of country performance, measured between years \emph{t+1} and \emph{t+4} after the election conducted at time \emph{t}. All estimates are expressed in percentage points.")


